package com.scy.jdbc;

import com.scy.jdbc.pojo.Account;

import java.sql.*;

public class JDBCDemo {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            //导入数据库的驱动包
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取数据库连接对象Connection
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/mydb",
                    "root",
                    "root"
            );
            //定义sql
            String sql = "select * from account";
            //获取执行sql语句的对象Statement（不能防止sql注入）
            //预编译对象，（创建对象时就要给一个sql语句，进行预编译）
            ps = conn.prepareStatement(sql);
            //执行sql调用方法去接受结果
            rs = ps.executeQuery();
            //处理结果集
            Account ac = new Account();
            //rs.next()=true 为有结果反之则无
            while (rs.next()){
                //获取结果集中的数据
                int id = rs.getInt("id");
                String name = rs.getString(2);
                double money = (double)rs.getObject("money");
//                System.out.println("id="+id+";name="+name+";money="+money);
                //对 对象赋值
                ac.setId(id);
                ac.setName(name);
                ac.setMoney(money);
                System.out.println(ac.toString());

            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //关闭资源
            if (rs!=null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (ps!=null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (conn!=null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

        }
    }
}
